﻿Imports System.ComponentModel

Public Class KeyedWindowBase
    Inherits ReWindow
    Implements IMessageListener

    Private Shared mOverrideGuard As New List(Of Type)

    Public Sub New()
        MyBase.New()
        Dim handledTypes As List(Of Type) = GetHandledMessageTypes()
        If handledTypes IsNot mOverrideGuard Then 'Check to make sure GetHandledTypes was overriden.
            For Each t As Type In GetHandledMessageTypes()
                MessageService.Instance.RegisterListener(t, Me)
            Next
        Else
            If Not DesignerProperties.GetIsInDesignMode(Me) Then
                Throw New Exception("You must override 'GetHandledMessageTypes' and return a list of message types this window handles.")
            End If
        End If
    End Sub

    Private Sub KeyedWindowBase_Closed(sender As Object, e As EventArgs) Handles Me.Closed
        For Each t As Type In GetHandledMessageTypes()
            MessageService.Instance.UnregisterListener(t, Me)
        Next
    End Sub

    Protected Overridable Function GetHandledMessageTypes() As List(Of Type)
        'Inheriting types MUST override this function, but WPF won't let the base class be abstract.
        'This guards against forgetting to override this function.
        'If the shared instance is detected then someone forgot to override the function
        Return mOverrideGuard
    End Function

    Public ReadOnly Property Key As Guid Implements IMessageListener.Key
        Get
            If Me.DataContext IsNot Nothing AndAlso TypeOf Me.DataContext Is KeyedViewModelBase Then
                Return CType(Me.DataContext, KeyedViewModelBase).Key
            Else
                Return Guid.Empty
            End If
        End Get
    End Property

    Private Sub MessageReceived(sender As KeyedViewModelBase, message As MessageBase) Implements IMessageListener.MessageReceived
        HandleMessage(sender, message)
    End Sub

    Protected Overridable Sub HandleMessage(sender As KeyedViewModelBase, message As MessageBase)

    End Sub

End Class
